package com.dfiov.cloud.msmtools.utils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import okhttp3.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JasperUtils {


    /**
     * 风神存量车SIM状态查询，postman方式，不含L7车型（P57 S01-F）
     * @return
     * @throws IOException
     */
    public static String getJasperSimStatus(String iccid) throws IOException {

        String sratus = "";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("text/xml; charset=utf-8");
            RequestBody body = RequestBody.create(mediaType, "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:sch=\"http://api.jasperwireless.com/ws/schema\">\n    <soapenv:Header>\n        <wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">\n            <wsse:UsernameToken>\n                <wsse:Username>Session12943</wsse:Username>\n                <wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">DFPV#session*api1</wsse:Password>\n            </wsse:UsernameToken>\n        </wsse:Security>\n    </soapenv:Header>\n    <soapenv:Body>\n        <sch:GetSessionInfoRequest>\n            <sch:messageId>123</sch:messageId>\n            <sch:version>1</sch:version>\n            <sch:licenseKey>1aaa80b9-901c-4e78-8d9c-247615786042</sch:licenseKey>\n            <!--1 or more repetitions:-->\n            <sch:iccid>" + iccid + "</sch:iccid>\n        </sch:GetSessionInfoRequest>\n    </soapenv:Body>\n</soapenv:Envelope>");
            Request request = new Request.Builder()
                    .url("https://api.10646.cn/ws/service/terminal")
                    .method("POST", body)
                    .addHeader("Content-Type", "text/xml; charset=utf-8")
                    .addHeader("SOAPAction", "http://api.jasperwireless.com/ws/service/terminal/GetSessionInfo")
                    .build();
            Response response = client.newCall(request).execute();
            String string = response.body().string();
//        Console.log(string);
            if (string.contains(iccid) && string.contains("ipAddress")) {
                sratus = "在线";
            } else {
                sratus = "离线";
            }
        } catch (Exception e) {
            sratus = "接口异常";
        }
        return sratus;
    }

    /**
     * 获取SIM状态，查看是否在线
     * @return  是否在线
     */
    public static String getSimStatus(String app_id , String app_secret , String openId, String iccid){

        // 定义API URL
        String url = "https://gwapi.10646.cn/api/wsGetSessionInfo/V1/1Main/vV1.1";

        String sratus = "";

        try {
            // 获取当前时间戳并格式化
            long currentTimestamp = System.currentTimeMillis();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); // 用于生成trans_id的格式
            String formattedDate = sdf.format(new Date(currentTimestamp));
            SimpleDateFormat sdfsss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); // 用于请求中的timestamp格式
            String timestamp = sdfsss.format(new Date(currentTimestamp));

            // 生成随机数并拼接成trans_id
            int randomNum = RandomUtil.randomInt(100000, 999999); // 生成6位随机数
            String trans_id = formattedDate + randomNum;

            // 拼接字符串并生成token（这里假设SmUtil.sm3是某个自定义的SM3哈希函数）
            String format = StrUtil.format("app_id{}{}timestamp{}{}trans_id{}{}", app_id, "", timestamp, "", trans_id, app_secret);
            // 注意：这里""是为了占位，确保format字符串的格式正确，因为StrUtil.format要求参数与占位符一一对应
            // 如果SmUtil.sm3不是您已有的函数，请替换为正确的SM3哈希实现
            String token = SmUtil.sm3(format).toLowerCase(); // 假设SmUtil.sm3返回大写，这里转为小写

            // 创建JSON对象
            JSONObject jsonObject = JSONUtil.createObj(); // 使用Hutool的简洁方法创建JSONObject

            // 填充JSON对象
            jsonObject.put("app_id", app_id);
            jsonObject.put("timestamp", timestamp);
            jsonObject.put("trans_id", trans_id);
            jsonObject.put("token", token);

            // 创建内层数据对象
            JSONObject dataObject = JSONUtil.createObj();
            dataObject.put("openId", openId);

            // 创建并填充ICCID数组
            JSONArray iccidsArray = JSONUtil.createArray();
            iccidsArray.add(iccid);
            dataObject.put("iccids", iccidsArray);

            // 将内层对象添加到外层对象
            jsonObject.put("data", dataObject);

            // 将JSON对象转换为字符串
            String jsonString = jsonObject.toStringPretty();

            // 使用OkHttp发送POST请求
            OkHttpClient client = new OkHttpClient(); // 无需再调用newBuilder().build()
            MediaType mediaType = MediaType.parse("application/json; charset=utf-8"); // 明确指定字符集
            RequestBody body = RequestBody.create(mediaType, jsonString);
            Request request = new Request.Builder()
                    .url(url)
                    .post(body) // 直接调用post方法，无需再指定method和body
                    .addHeader("Content-Type", mediaType.toString()) // 使用mediaType.toString()获取完整的MIME类型
                    .build();

            // 执行请求并获取响应
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }
                // 打印响应体
                String responseBody = response.body().string();
//            System.out.println(responseBody);
                if (responseBody.contains(iccid) && responseBody.contains("ipAddress")) {
                    sratus = "在线";
                } else {
                    sratus = "离线";
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        } catch (Exception e) {
            sratus = "接口异常";
        }
        return sratus;
    }

}
